package com.tt.utils;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

/**
 * @Title: JWTUtils
 * @Author zl
 * @Package com.ttio.utils
 * @Date 2025/2/5 14:45
 * @description: token生成工具类
 */
public class JWTUtils {
    private static final String SING = "15b51fce28cc6c8d04c98b223ce84e0a";

    /**
     * 生成Token  header.payload.sign
     */
    public static String getToken(String content) {
        Calendar instance = Calendar.getInstance();
        //默认7天过期
        instance.add(Calendar.DATE, 7);
        //创建jwt builder
        JWTCreator.Builder builder = JWT.create();
        builder.withClaim("content", EncryptionUtils.encryptDES(content,SING));
        String token = builder.withExpiresAt(instance.getTime())
                .sign(Algorithm.HMAC256(SING));
        return token;
    }

    /**
     *  验证token的合法性
     */
    public static boolean verify(String token){
        try{
            //这一行代码就可以起到验证的作用，因为在验证不匹配时它自动会抛出异常
            JWT.require(Algorithm.HMAC256(SING)).build().verify(token);
            return true;
        }catch (Exception e){
            return false;
        }
    }

    /**
     * 获取token的信息方法
     */
    public static String getTokenInfo(String token){
        DecodedJWT verify = JWT.require(Algorithm.HMAC256(SING)).build().verify(token);
        String content = EncryptionUtils.decryptDES(verify.getClaim("content").as(String.class), SING);
        return content;
    }

    public static void main(String[] args) {

        Map<String,Object> maps = new HashMap<>();
        maps.put("userId",1);
        maps.put("data","lisi");
        String token1 = JWTUtils.getToken(JSONUtil.toJsonStr(maps));
        String encryptAES = EncryptionUtils.encryptDES(JSONUtil.toJsonStr(maps), SING);
        System.out.println(encryptAES);
        System.out.println(EncryptionUtils.decryptDES(encryptAES, SING));

        System.out.println(token1);
        token1 = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE3NTEzNDg1MTQsImNvbnRlbnQiOiJzOVpoR21TOTRMa1JjSnVXNGVkOW81NXpGM2IwendVSndhbksyWXBqYW84WEsyZmlhdnovOUp0alo1YW5pbm9RY0pBYzVZZkNRRlhybFByclhOTWFzSXZ4eVhQQkJzdEFCVmFMNjM5eFlMVlZWSkxRZlFvT09zeWJtV3dxUEJnUkF6WU81VGRRSnB0SXlPU2k5c3JFSHdCdHUrNXJFU1RPTmRmdU40RkN6am89In0.p5YY295bQChyGJnls67-ExhWcFWKhFNvOOaGpZey1eI";
        System.out.println(JWTUtils.verify(token1));
        System.out.println(JWTUtils.getTokenInfo(token1));
    }
}
